package com.kingsoft.dc.khaos.module.spark.util

import com.kingsoft.dc.khaos.module.spark.metadata.source.CosReplaceContentInfo
import org.apache.commons.lang3.StringUtils

/**
  *  2021-7-9 czc
  *  hdfs 和 cos 文本内容替换功能 实现
  */
object FieldsContentUtils {
  /**
    * 字段内容替换
    *
    * @param lineArr
    * @param replaceInfos
    * @return
    */
  def replaceFieldsContent(lineArr: Array[String],
                           replaceInfos: List[CosReplaceContentInfo]):Array[String] = {
    lineArr.map(col => {
      var field = col.trim
      for (i <- replaceInfos) {
        if (i.replace_type.equalsIgnoreCase("field")) {
          if (StringUtils.isBlank(field)) {
            if (i.source.equals("{NULL}")) {
              field = i.target
            }
          } else {
            field = i.scope match {
              case "all" => field.replaceAllLiterally(i.source, i.target) //全部替换
              case "pre" => StringHandleUtils.replacePrefix(field, i.source, i.target) //替换前缀
              case "suf" => StringHandleUtils.replaceSuffix(field, i.source, i.target) //替换后缀
              case "pre_suf" => StringHandleUtils.replacePrefixAndSuffix(field, i.source, i.target) //替换前后缀
            }
          }
        }
      }
      field
    })
  }

  /**
    * 字段内容替换
    * @param lineArr
    * @param replaceInfos
    * @return
    */
  def replaceFieldsContent(lineArr: Array[String],
                           replaceInfos: List[CosReplaceContentInfo],
                           delimiter: String):String = {
    val newlineArr = replaceFieldsContent(lineArr,replaceInfos)
    newlineArr.mkString(delimiter)
  }

  /**
    * 数据行内容替换
    *
    * @param line
    * @param replaceInfos
    * @return
    */
  def replaceLineContent(line: String, replaceInfos: List[CosReplaceContentInfo]): String = {
    var lineStr = line.trim
    for (i <- replaceInfos) {
      val replaceType = i.replace_type
      val source = i.source
      val target = i.target
      val scope = i.scope
      if (replaceType.equalsIgnoreCase("line")) {
        lineStr = scope match {
          case "all" => line.replaceAllLiterally(source, target) //全部替换
          case "pre" => StringHandleUtils.replacePrefix(line, source, target) //替换前缀
          case "suf" => StringHandleUtils.replaceSuffix(line, source, target) //替换后缀
          case "pre_suf" => StringHandleUtils.replacePrefixAndSuffix(line, source, target) //替换前后缀
        }
      }
    }
    lineStr
  }
}
